﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE;

namespace AutomationFoundation.CodeToolKit.VisualStudio.Linq
{
    internal sealed class ProjectItemIterator:IEnumerable<ProjectItem>
    {
        #region Class Fields

        private ProjectItems _items;

        #endregion

        #region Constructor
        public ProjectItemIterator(ProjectItems projectItems)
        {
            if (projectItems == null)
            {
                throw new ArgumentNullException("projectItems");
            }
            _items = projectItems;
        }

        #endregion

        #region IEnumerable<ProjectItem> Members

        public IEnumerator<ProjectItem> GetEnumerator()
        {
            return (EnumerateProjectItems(_items).Select(P=>P)).GetEnumerator();               
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion

        #region Private
        private IEnumerable<ProjectItem> EnumerateProjectItems(ProjectItems items)
        {
            ProjectItems children;
            foreach (ProjectItem item in items)
            {
                yield return item;

                children = null;
                try
                {
                    children = item.ProjectItems;
                }
                catch (NotImplementedException)
                {
                    children = null;
                }
                if (children != null)
                {
                    foreach (ProjectItem child in EnumerateProjectItems(children))
                    {
                        yield return child;
                    }
                }
            }
        }
        #endregion
    }
}
